package com.csw.flink.kafka

import java.util.Properties

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}

object Demo03TS {
  def main(args: Array[String]): Unit = {


    /**
      * 创建生产者
      *
      */
    //创建配置文件对象
    val properties = new Properties()
    //kafka  broker 地址列表
    properties.setProperty("bootstrap.servers", "master:9092,node1:9092,node2:9092")
    //key和value序列化的类
    properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    properties.setProperty("transactional.id","csw")

    val producer: KafkaProducer[String, String] = new KafkaProducer[String,String](properties)
    /**
      * 使用kafka  事务
      */

    //初始化事务
    producer.initTransactions()

    //开始事务
    producer.beginTransaction()

    println("发送第一条数据")

    producer.send(new ProducerRecord[String,String]("ts","java"))

    Thread.sleep(5000)

    println("发送第二条数据")
    producer.send(new ProducerRecord[String,String]("ts","spark"))

    //提交事务
    producer.commitTransaction()

    //刷新事务
    producer.flush()

    //关闭事务
    producer.close()

    /**
      * 在kafka中创建消费者：
      * kafka-console-consumer.sh --bootstrap-server  master:9092,node1:9092,node2:9092 --isolation-level read
      * _committed  --from-beginning --topic ts
      *
      * --isolation-level：读取模式    read_committed：读已经提交的
      */
  }
}
